import Vue from 'vue'
import VueRouter from 'vue-router'
// import login from '../views/login.vue'
// import detail from '../views/detail.vue'
// import layout from '../views/layout.vue'
// import register from '../views/register.vue'
// import article from '../views/article.vue'
// import collect from '../views/collect.vue'
// import like from '../views/like.vue'
// import user from '../views/user.vue'
import { getToken } from '@/utils/storage'
import { Toast } from 'vant'
Vue.use(VueRouter)

const routes = [
  { path: '/login', component: () => import('../views/login.vue') },
  { path: '/detail/:id', component: () => import('../views/detail.vue') },
  { path: '/register', component: () => import('../views/register.vue') },
  {
    path: '/',
    component: () => import('../views/layout.vue'),
    redirect: '/article',
    children: [
      { path: '/article', component: () => import('../views/article.vue') },
      { path: '/like', component: () => import('../views/like.vue') },
      { path: '/user', component: () => import('../views/user.vue') },
      { path: '/collect', component: () => import('../views/collect.vue') }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 注册全局前置守卫
// 一旦注册了全局前置守卫, 那守卫就生效了, 所有的页面跳转必须由守卫来放行
// router.beforeEach
// 传一个回调函数
// 回调函数有三个参数
// to: 到哪里去
// from: 从哪里来
// next: 函数, 决定是否放行
// next() 表示放行, 调用 next(false) 表示不放行, 调用 next('路径') 表示强行跳转到指定路径
// to和form 是参数，
router.beforeEach((to, form, next) => {
  // console.log(to.path, form.path)
  // 调用next()表示放行，调用next(false)表示不放行，
  // 调用next('路径')，表示强行跳转到指定路径
  // next()是函数
  // next()
  // 获取token
  const token = getToken()
  const whiteList = ['/register', '/login']
  // 判断是否有token
  if (token) {
    // 有token 放行
    next()
  } else {
    // 没有则判断是否是白名单里的
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
      Toast.fail('请登录')
    }
  }
})

export default router
